import logging

from config.common import DM_DATABASE
from store.dm.dm_client import DmClient
from concurrent.futures import ThreadPoolExecutor
from handler.xjxc_general_handler import parse_oss_pdf
from handler.xjxc_parse_result import XjxcParseResult
from datetime import datetime
from handler.history_scheduling_general_handler import parse_oss_excel


class StoreHandler:
    def __init__(self):
        self.dm_client: DmClient = None
        self.executor = ThreadPoolExecutor(max_workers=5)

    def init_config(self):
        self.dm_client = DmClient()

    # 解析并入库巡检巡查数据
    def parse_and_store_xjxc_result(self, doc_id, doc_name, pdf_path):
        try:
            # 更新解析状态为解析中
            self.update_doc_status(doc_id, 1)
            results: list[XjxcParseResult] = parse_oss_pdf(pdf_path, doc_name)
            if not results or len(results) < 1:
                logging.error('%s文档解析为空', pdf_path)
                # 更新解析状态为失败
                self.update_doc_status(doc_id, 3)
                return

            # 如果文档doc_id已经存在解析记录，则删除
            self.dm_client.execute_query(f"delete from {DM_DATABASE}.T_PATROL_RECORD where DOC_ID = ?", (doc_id,),
                                         commit=True)

            for result in results:
                insert_sql = (f"""
                    insert into {DM_DATABASE}.T_PATROL_RECORD("PROJECT_NAME", "TASK_NAME", "INSPECT_PERSON", 
                        "INSPECT_DATE", "IMAGES", "DOC_ID", "CREATE_TIME")
                    values(?, ?, ?, ?, ?, ?, ?)
                """)
                self.dm_client.execute_query(insert_sql, (
                    result.project_name, result.task_name, result.inspect_person,
                    datetime.strptime(result.inspect_date, '%Y-%m-%d'), result.images,
                    doc_id, datetime.now()), commit=True)
            # 更新解析状态为成功
            self.update_doc_status(doc_id, 2)
            logging.info('解析入库成功：{}'.format(pdf_path))
        except Exception as e:
            logging.error('%s解析失败', pdf_path, e)
            self.update_doc_status(doc_id, 3)

    # 解析并入库历史调度过程数据
    def parse_and_store_history_scheduling_process_result(self, doc_id, doc_name, excel_path):
        try:
            # 更新解析状态为解析中
            self.update_doc_status(doc_id, 1)
            results = parse_oss_excel(excel_path)
            if not results or len(results) < 1:
                logging.error('%s文档解析为空', excel_path)
                # 更新解析状态为失败
                self.update_doc_status(doc_id, 3)
                return

            # 如果文档doc_id已经存在解析记录，则删除
            self.dm_client.execute_query(f"delete from {DM_DATABASE}.T_HIS_SCHEDULING_PRCESS where DOC_ID = ?",
                                         (doc_id,),
                                         commit=True)

            for result in results:
                insert_sql = (f"""
                    insert into {DM_DATABASE}.T_HIS_SCHEDULING_PRCESS("SCHEDULING_DATE", "SCHEDULING_COUNT", 
                    "HOLE_COUNT", "DISPLACEMENT", "MAX_FLOW", "SCHEDULING_TIME", 
                    "OPEN_ALTITUDE", "UPSTREAM_WATER_LEVEL", "DOWNSTREAM_WATER_LEVEL", "WATER_HEAD", 
                    "SINGLE_WIDTH_FLOW", "SINGLE_WIDTH_FLOW_2", "CREATE_TIME", "DOC_ID")
                    values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """)
                self.dm_client.execute_query(insert_sql, (
                    result.get('scheduling_date'), result.get('scheduling_count'),
                    result.get('hole_count'), result.get('displacement'), result.get('max_flow'),
                    result.get('scheduling_time'), result.get('open_altitude'), result.get('upstream_water_level'),
                    result.get('downstream_water_level'), result.get('water_head'), result.get('single_width_flow'),
                    result.get('single_width_flow_2'), datetime.now(), doc_id), commit=True)
            # 更新解析状态为成功
            self.update_doc_status(doc_id, 2)
            logging.info('解析入库成功：{}'.format(excel_path))
        except Exception as e:
            logging.error('%s解析失败', excel_path, e)
            self.update_doc_status(doc_id, 3)

    # 更新文档解析状态
    def update_doc_status(self, doc_id, status):
        self.dm_client.execute_query(f"update {DM_DATABASE}.T_DOCUMENTS set KB_STATUS = ? where ID = ?",
                                     (status, doc_id),
                                     commit=True)
